package com.example.filelock.utils;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.filelock.MainActivity;
import com.example.filelock.R;
import com.example.filelock.entity.FileViewEntity;
import com.rey.material.app.BottomSheetDialog;

import java.io.File;

public class LogOnFileItem {
    Context context;
    BottomSheetDialog bottomSheetDialog;
    SharedPreferences sp;

    public LogOnFileItem(Context context) {
        this.context = context;
        sp = context.getSharedPreferences(BasDataUtil.SP_MAIN,Context.MODE_PRIVATE);
    }

    /**
     * 点击了列表文件
     *
     * @param object：文件对象
     * @param isEnOrDe    ：true加密页还是false解密页
     */
    public void onItemFileSet(final FileViewEntity object, final boolean isEnOrDe) {
        View logView = LayoutInflater.from(context).inflate(R.layout.log_encryption_file, null);
        //实例化对话框
        bottomSheetDialog = new BottomSheetDialog(context);
        //底部对话框
        bottomSheetDialog
                .contentView(logView)          //获取键时用了view那么此时一点要用view否则就获取不到点击事件
                .inDuration(100)
                .outDuration(100)
                .cancelable(true)
                .show();
        LinearLayout layout_unPwd = logView.findViewById(R.id.log_encryption_file_tv1);
        TextView tv_text = logView.findViewById(R.id.log_encryption_file_tv1_text);
        tv_text.setText(isEnOrDe ? sp.getBoolean(BasDataUtil.SP_AutoFIle,true)?"临时解密":"解密" : "打开");
        LinearLayout layout_shareFile = logView.findViewById(R.id.log_encryption_file_tv4);
        LinearLayout layout_deleteFile = logView.findViewById(R.id.log_encryption_file_tv2);
        LinearLayout layout_copeFile = logView.findViewById(R.id.log_encryption_file_tv3);
//                    点击了解密/或打开
        layout_unPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEnOrDe) {
                    //解密
                    final View logView = LayoutInflater.from(context).inflate(R.layout.log_decryption_view, null);
                    final EditText ev_pwd = logView.findViewById(R.id.log_encryption_et_pwd);
                    AlertDialog alertDialog = new AlertDialog.Builder(context)
                            .setTitle("解密文件")
                            .setView(logView)
                            .setNegativeButton("取消", null)
                            .setPositiveButton("解密", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        String s_pwd = ev_pwd.getText().toString();
                                        if (s_pwd.equals("")) {
                                            Toast.makeText(context, "不能为空!", Toast.LENGTH_SHORT).show();
                                        } else if (s_pwd.length() < 3 || s_pwd.length() > 6) {
                                            Toast.makeText(context, "密码长度不符合!", Toast.LENGTH_SHORT).show();
                                        } else {
                                            File file = new File(object.getFilePath());
                                            LoadingFile loadingFile = new LoadingFile(context, file.length());
                                            if (!loadingFile.decryptionFile(object.getFilePath(), s_pwd)) {
                                                Toast.makeText(context, "文件为空", Toast.LENGTH_SHORT).show();
                                            }
                                            loadingFile.addLoadingOk(new LoadingFile.LoadingFileOk() {
                                                @Override
                                                public void onLoadingOk() {
                                                    LogCompete.onLoadingOkCompete();
                                                }
                                            });
                                        }

                                    } catch (Exception e) {
                                        Log.d(BasDataUtil.LOG_TOAST,"底部框错误:"+e.toString());
                                    }

                                }
                            })
                            .show();
                } else {
                    //打开
                    openFileByPath(context, object.getFilePath());
                }

                bottomSheetDialog.cancel();
            }
        });
//                点击了共享
        layout_shareFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                //设置intent的data和Type属性。
                intent.setType("*/*");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(object.getFilePath()))); // 必须添加这一句，否则找不到资源
                context.startActivity(intent);
            }
        });
//                    点击删除
        layout_deleteFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileUtil.deleteFile(object.getFilePath(), context);
                bottomSheetDialog.cancel();
//                删除成功后回调
                if (LogCompete != null)
                    LogCompete.onDeleteCompete();
            }
        });
//                    点击复制路径
        layout_copeFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                Uri copyUri = Uri.parse(object.getFilePath());
                ClipData clipData = ClipData.newUri(context.getContentResolver(), "URL", copyUri);
                clipboardManager.setPrimaryClip(clipData);
                bottomSheetDialog.cancel();
                Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //    点击删除回调出去
    LogCompete LogCompete = null;

    public interface LogCompete {
        void onDeleteCompete();
        void onLoadingOkCompete();
    }

    public void addLogCompete(LogCompete deleteCompete) {
        this.LogCompete = deleteCompete;
    }
//    打开文件方法

    /**
     * 根据路径打开文件
     *
     * @param context 上下文
     * @param path    文件路径
     */
    public static void openFileByPath(Context context, String path) {
        if (context == null || path == null)
            return;
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        //文件的类型
        String type = "";
        for (int i = 0; i < BasDataUtil.MATCH_ARRAY.length; i++) {
            //判断文件的格式
            if (path.toString().contains(BasDataUtil.MATCH_ARRAY[i][0].toString())) {
                type = BasDataUtil.MATCH_ARRAY[i][1];
                break;
            }
        }
        try {
            //设置intent的data和Type属性
            intent.setDataAndType(Uri.fromFile(new File(path)), type);
            //跳转
            context.startActivity(intent);
        } catch (Exception e) { //当系统没有携带文件打开软件，提示
            Toast.makeText(context, "无法打开该格式文件!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}
